import numpy as np
import torch

# 从列表创建
t1 = torch.tensor([[1, 2, 3]])

# 从numpy创建
n = np.array([[1, 2, 3]])
t2 = torch.from_numpy(n)

# tensor转numpy
a = torch.rand((1, 3))
b = a.numpy()

# 指定维度随机创建
t3 = torch.rand((1, 3))

# 指定维度标准正态分布随机创建
t3 = torch.normal(mean=2,std=3,size=(4,5)) # 得到一个(4,5)形状,随机方式维均值为2，方差为3

# 移动至cuda/cpu
t1 = t1.to("cuda")

# 生成 tensor([0, 1, 2, 3, 4])
t4 = torch.arange(start=0, end=5, step=1)

# 张量连接
a = torch.rand((1, 2))
b = torch.rand((2, 2))
c = torch.cat([a, b], dim=0)

# 张量分割成指定份
d, f = torch.chunk(input=b, chunks=2, dim=0)

# 张量划分为指定维度
a = torch.rand((3,5))
b,c,d = torch.split(a,[1,2,2],dim=1)

# 维度变换，不改变元素顺序
a = torch.rand((2, 3))
b = torch.reshape(a, shape=(3, 2))
c = torch.reshape(a, shape=(1, -1))

# 维度变换，改变元素顺序,转置
a = torch.rand((2,3,5))
b = torch.transpose(a,dim0=0,dim1=2) # 交换第0维与第2维，得到(5,3,2)

# 张量降维
a = torch.rand((3,5,1))
b = torch.squeeze(a,dim=2)

# 张量降维
a = torch.rand((3,5))
b = torch.unsqueeze(a,dim=1)

# 拷贝
a = torch.rand((3,5))
b = torch.tile(a,(2,2)) # 第一维复制两份，第二维复制两份，得到(6,10)
c = torch.tile(a,(2,1)) # 第一维复制两份，第二维复制1份，得到(6,5)

# 按照特定维度拆开
a = torch.rand((3,5,4))
b,c,d = torch.unbind(a,dim=0)  # (3,5,4) -> (5,4) (5,4) (5,4)

# 三目运算符
a = torch.tensor([0.,1.])
b = torch.tensor([1.,2.])
c = torch.where(a!=0.,a,b)  # a中等于0.时保留b对应元素，a中等于0.时保留a中元素

# 填充mask
eye_mask = torch.eye(3,dtype=bool)  # 创建[3,3]的布尔对角阵(对角线为True)
x = torch.randn(3,3)
y = x.masked_fill(eye_mask, 0)  # 再eye_mask Ture的对应地方填写0


print("完结撒花！")
